
from django.shortcuts import render

# Create your views here.
from django.views import View

'''
    {# 2,分类广告 #}
    <ul class="sub_menu">
        {% for group in categories.values() %}
        # 需要构建一个categories字典，键值对为“编号：频道组” --->遍历得到频道组

        <li>
            <div class="level1">
                {% for channel in group.channels %}
                # 将每一个频道组以字典形式定义，键值对为“channels：频道” -->遍历得到频道

                <a href="{{ channel.url }}">{{ channel.name }}</a>
                {% endfor %}
            </div>
            <div class="level2">
                {% for cat2 in group.sub_cats %}
                # 在每一个字典形式的频道中添加二级子频道键值对——“sub_cats：二级子频道” -->遍历得到二级子频道

                <div class="list_group">
                    <div class="group_name fl">{{ cat2.name }} &gt;</div>
                    <div class="group_detail fl">
                        {% for cat3 in cat2.subs.all() %}
                        # 获取二级子频道的所有子频道，遍历得到三级子频道

                        <a href="/list/{{ cat3.id }}/1/">{{ cat3.name }}</a>
                        {% endfor %}
                    </div>
                </div>
                {% endfor %}
            </div>
        </li>
        {% endfor %}
    </ul>

由前端代码推导，需要以此格式返回数据
categories = {id1:group,id2:group,...}
group = {channels:[channel1,channel2,...],sub_cats:[cat2_1,cat2_2,...]}
channel.url, channel.name
cat2.name
cat3.id, cat3.name
'''

from goods.models import GoodsChannel

class IndexView(View):
    def get(self,request):
        # 1,创建字典
        # 01 categories = {id1:group,id2:group,...}
        categories = {}

        # 2,获取所有频道，构建频道组channels
        # 02 group = {'channels':[channel1,channel2,...], 'sub_cats':[cat2_1,cat2_2,...]}
        channels = GoodsChannel.objects.order_by('group_id','sequence')

        # 3,根据组id对频道分类
        for channel in channels:
            group_id = channel.group_id
            if group_id not in categories:
                categories[group_id] = {'channels': [], 'sub_cats': []}

            # 将频道添加至channels的value列表
            # 组织数据,获取频道对应的商品分类
            category = channel.category
            catetory_dict = {
                "id":category.id,
                "name":category.name,
                "url":channel.id,
            }
            categories[group_id]['channels'].append(catetory_dict)

            # 获取频道的子频道
            for cat2 in category.subs.all():
                # cat2已经是数据表对象，不用再做数据组织
                categories[group_id]['sub_cats'].append(cat2)


        # 4,获取广告数据
        contents = {}
        from contents.models import ContentCategory
        content_catetories = ContentCategory.objects.all()

        for content_catetorie in content_catetories:
            contents[content_catetorie.key] = content_catetorie.content_set.order_by('sequence')

        # 5,拼接数据,返回响应
        context = {
            "categories":categories,
            "contents": contents
        }
        return render(request, 'index.html',context=context)
